package demo.dynamic.wapper.java;

import demo.dynamic.util.ClassUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 */
public class JavaCompilerFactory {

    /** javaFileObjectMap */
    //存放编译之后的字节码(key:类全名,value:编译之后输出的字节码)
    private static final Map<String, JavaCompile> javaFileObjectMap = new ConcurrentHashMap<>();

    /**
     * Gets compiler *
     *
     * @param sourceCode source code
     * @return the compiler
     * @since 1.0.0
     */
    public static JavaCompile getCompiler(String sourceCode) {
        Assert.isTrue(!StringUtils.isBlank(sourceCode), "脚本不能为空");
        String fullClassName = ClassUtils.getFullClassName(sourceCode);
        Assert.isTrue(!StringUtils.isBlank(fullClassName), "无法解析类名，检查脚本代码是否有误");
        return javaFileObjectMap.computeIfAbsent(fullClassName,
                                                                    key -> new JavaCompile(sourceCode));
    }

    /**
     * Remove compiler
     *
     * @param fullClassName full class name
     * @since 1.0.0
     */
    public static void removeCompiler(String fullClassName) {
       javaFileObjectMap.remove(fullClassName);
    }

}
